<script lang="ts" setup>
import { useVbenDrawer } from '@vben/common-ui';

import { message } from 'ant-design-vue';

import { useVbenForm } from '#/adapter';
import { saveDesignerApi } from '#/api/core/designer';
import { $t } from '#/locales';

defineOptions({
  name: 'DesignerDrawer',
});

const props = defineProps<{
  onSave: () => void;
}>();

const [Form, formApi] = useVbenForm({
  commonConfig: {
    componentProps: {
      class: 'w-full',
    },
  },
  handleSubmit: onSubmit,
  schema: [
    {
      component: 'Input',
      componentProps: {
        type: 'hidden',
      },
      fieldName: 'id',
    },
    {
      component: 'Input',
      componentProps: {
        type: 'hidden',
      },
      fieldName: 'redirect',
    },
    {
      component: 'Input',
      componentProps: {
        placeholder: '请输入菜单名称',
      },
      fieldName: 'name',
      label: '菜单名称',
      rules: 'required',
    },
    {
      component: 'Input',
      componentProps: {
        placeholder: '请输入表名称',
      },
      fieldName: 'tableName',
      label: '表名称',
      rules: 'required',
    },
    {
      component: 'Select',
      componentProps: {
        placeholder: '请选择页面布局',
        options: [
          { label: '单页布局', value: 'single' },
          { label: '导航布局', value: 'navigation' },
          { label: '多条件布局', value: 'multi' },
        ],
      },
      fieldName: 'layout',
      label: '页面布局',
      rules: 'required',
    },
    {
      component: 'Input',
      componentProps: {
        placeholder: '请输入描述',
        type: 'textarea',
      },
      fieldName: 'description',
      label: '描述',
    },
  ],
  showDefaultActions: false,
});

async function onSubmit(values: Record<string, any>) {
  try {
    await saveDesignerApi(values);
  } catch (error: any) {
    console.error('保存失败:', error);
    throw new Error(error.message || '提交失败');
  }
}

const [Drawer, drawerApi] = useVbenDrawer({
  async onOpenChange(data) {
    if (data) {
      const values = drawerApi.getData<Record<string, any>>();
      if (values) {
        formApi.setValues(values);
      }
    } else {
      formApi.setValues({});
    }
  },
  onCancel() {
    drawerApi.close();
  },
  onConfirm: async () => {
    const isValid = await formApi.validate();
    if (isValid.valid) {
      try {
        const values = formApi.form.values;
        await formApi.submitForm();
        drawerApi.close();
        message.success(
          values.id
            ? $t('common.action.editSuccess')
            : $t('common.action.addSuccess'),
        );
        props.onSave();
      } catch (error: any) {
        console.error('提交失败:', error);
        message.error(error.message || $t('common.submit.failed'));
      }
    } else {
      message.error($t('common.form.required'));
    }
  },
});
</script>

<template>
  <Drawer :title="formApi.form.values?.id ? '编辑' : '新增'">
    <Form />
  </Drawer>
</template>
